package jp.ac.kobe_u.cs.cream;

import jp.ac.kobe_u.cs.cream.*;
import java.util.*;

public class IBBSearch extends LocalSearch {
    private double clearRate = 0.8;

    public IBBSearch(Network network) {
	this(network, DEFAULT, null);
    }

    public IBBSearch(Network network, int option) {
	this(network, option, null);
    }

    public IBBSearch(Network network, String name) {
	this(network, DEFAULT, name);
    }

    public IBBSearch(Network network, int option, String name) {
	super(network, option, name);
	setExchangeRate(0.8);
    }

    public void setIterationTimeout(long time) {
	iterationTimeout = time;
    }

    public void setClearRate(double rate) {
	clearRate = rate;
    }

    protected void bbSearch() {
	if (isAborted())
	    return;
	for (solver.start(iterationTimeout); solver.waitNext(); solver.resume()) {
	    solution = solver.getSolution();
	    success();
	    if (isAborted())
		break;
	}
	solver.stop();
	solution = solver.getBestSolution();
    }

    protected void startSearch() {
	solver = new DefaultSolver(network, option);
	//solution = solver.findFirst();
	//solution = solver.findBest(iterationTimeout);
	bbSearch();
    }

    protected void nextSearch() {
	if (isAborted())
	    return;
	solution = candidate();
	Code code = solution.getCode();
	code = (Code)code.clone();
	Condition conditions[] = code.conditions;
	for (int i = 0; i < conditions.length; i++) {
	    if (Math.random() < clearRate) {
		conditions[i] = null;
	    }
	}
	code.setTo(network);
	bbSearch();
    }
}
